package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.customerview.adapter.BottomDialogAdapter
import com.zat.mes.andrmes.data.MacCheckBean
import com.zat.mes.andrmes.data.MathineBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.main.vm.BindMachineModel
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.MachineModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.DateUtil
import com.zat.mes.andrmes.utils.DisplayUtil
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_in_house.*
import kotlinx.android.synthetic.main.activity_mac_check.*
import kotlinx.android.synthetic.main.activity_mac_check_add.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.layout_title_right_text.view.*
import permissions.dispatcher.*
import java.util.*

@RuntimePermissions
class MacCheckAddActivity : BaseActivity() {

    private var macUpDateCheckBean: MacCheckBean?=null
    var qcModel: QcPlanViewModel? = null
    var machineModel: MachineModel? = null
    var macCheckTypes: MutableList<ParantTypeItem>? = null
    var dateSelectTypes: MutableList<ParantTypeItem>? = null
    var madModel: BindMachineModel? = null
    var shifts = ""
    var timeSlot = ""
    var mathineBean: MathineBean? = null
    var mAdapter: BottomDialogAdapter? = null
    override fun init() {
        initView()
        initData()
    }

    private fun initData() {
        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getParantTypeData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it.containsKey("OPERATE_AUDIT_RECORD")) {
                macCheckTypes = it.get("OPERATE_AUDIT_RECORD")
            } else if (it.containsKey("TIME_SLOT")) {
                dateSelectTypes = it.get("TIME_SLOT")
            }
        })
        qcModel?.loadParantTypeList("OPERATE_AUDIT_RECORD")
        Handler().postDelayed(Runnable { qcModel?.loadParantTypeList("TIME_SLOT") }, 1000)

        madModel = ViewModelProvider(this).get(BindMachineModel::class.java)
        madModel?.getMathine()?.observe(this, Observer {
            if (it == null) {
                showToast("未查到相关机器")
            }
            mathineBean = it
            tvMacNo.text = "设备编码：" + mathineBean?.macNo
            //去查询是否有过新增，如果有则修改，如果没有则新增。
            machineModel?.getMachineCheck(mathineBean?.macNo,DateUtil.formatDate(Date(),DateUtil.FORMAT_3),shifts,timeSlot)


        })
        mAdapter = BottomDialogAdapter(R.layout.item_dialog_bottom)
        rvMacAdd.layoutManager = LinearLayoutManager(this)
        rvMacAdd.adapter = mAdapter

        machineModel = ViewModelProvider(this).get(MachineModel::class.java)
        //新增返回
        machineModel?.getAddMachineData()?.observe(this, Observer {
            closeLoading()
            showToast(it)
            mathineBean = null
            tvMacNo.text = "设备编码"
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
        })

        machineModel?.getMachineData()?.observe(this, Observer {
            closeLoading()
            mAdapter?.setNewData(macCheckTypes)
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
            if (it==null || it.size<=0){
                btnAddMac.text = "新增"
            }else{
                macUpDateCheckBean = it[0]
                try {
                    if(macUpDateCheckBean?.brandChecker=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(0)!!)
                    }
                    if(macUpDateCheckBean?.cylinderCheck=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(1)!!)
                    }
                    if(macUpDateCheckBean?.checkData=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(2)!!)
                    }
                    if(macUpDateCheckBean?.characters=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(3)!!)
                    }
                    if(macUpDateCheckBean?.checking=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(4)!!)
                    }
                    mAdapter?.notifyDataSetChanged()
                    btnAddMac.text = "修改"
                }catch (e:java.lang.Exception){}

            }
        })
    }

    private fun initView() {
        setContentView(R.layout.activity_mac_check_add)
        tVtitle.text = "新增机器检查"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        val inflate = LayoutInflater.from(this).inflate(R.layout.layout_title_right_text, null)
        inflate.tvTitleRight.text = "检查历史"
        rlRightComm.addView(inflate)
        rlRightComm.visibility = View.VISIBLE
        val layoutParams: RelativeLayout.LayoutParams =
            inflate.layoutParams as RelativeLayout.LayoutParams
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
        layoutParams.rightMargin = DisplayUtil.dip2px(this, 30f)
        rlRightComm.setOnClickListener {
            startActivity(Intent(this,MacCheckActivity::class.java))
        }
        btnScanMacAdd.setOnClickListener {
            if (TextUtils.isEmpty(shifts)) {
                showToast("请选择白班或晚班")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(timeSlot)) {
                showToast("请选择时间段")
                return@setOnClickListener
            }
            showCameraWithPermissionCheck()

        }
        rgMacAdd.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                rbMacAddDay.id -> shifts = "1"
                rbMacAddNight.id -> shifts = "2"
            }
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
            btnAddMac.text =  "新增"
            mathineBean = null
            tvMacNo.text = "设备编码"
        }
        btnDateSelect.setOnClickListener {
            showBottomDialog(dateSelectTypes)
        }
        btnAddMac.setOnClickListener {
            if (TextUtils.isEmpty(shifts)) {
                showToast("请选择白班或晚班")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(timeSlot)) {
                showToast("请选择时间段")
                return@setOnClickListener
            }
            if (mathineBean == null) {
                showToast("请扫机器码")
                return@setOnClickListener
            }
            //提交
            if (btnAddMac.text == "新增") {
                val macCheckBean = MacCheckBean()
                macCheckBean.shifts = shifts
                macCheckBean.machineNo = mathineBean?.macNo
                macCheckBean.timeSlot = timeSlot
                macCheckBean.workDay = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "brandChecker" -> macCheckBean.brandChecker = "1"
                        "characters" -> macCheckBean.characters = "1"
                        "cylinderCheck" -> macCheckBean.cylinderCheck = "1"
                        "checkData" -> macCheckBean.checkData = "1"
                        "checking" -> macCheckBean.checking = "1"
                    }
                }
                machineModel?.addMachineCheck(macCheckBean)
            }else{
                //修改
                macUpDateCheckBean?.brandChecker = "0"
                macUpDateCheckBean?.characters = "0"
                macUpDateCheckBean?.cylinderCheck = "0"
                macUpDateCheckBean?.checkData = "0"
                macUpDateCheckBean?.checking = "0"
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "brandChecker" -> macUpDateCheckBean?.brandChecker = "1"
                        "characters" -> macUpDateCheckBean?.characters = "1"
                        "cylinderCheck" -> macUpDateCheckBean?.cylinderCheck = "1"
                        "checkData" -> macUpDateCheckBean?.checkData = "1"
                        "checking" -> macUpDateCheckBean?.checking = "1"
                    }
                }
                machineModel?.upDateMachineCheck(macUpDateCheckBean!!)
            }
            showLoading()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查机器
            showLoading()
            madModel?.selectMacByQr(qrCode);

        }
    }

    /**
     * 显示底部弹框 处理方式
     */
    fun showBottomDialog(list: MutableList<ParantTypeItem>?) {
        BottomSignDailog(this, list, object : BottomSignDailog.OnBottomSelectListener {
            override fun onBottomSelect(parantTypeItem: ParantTypeItem) {
                btnDateSelect.text = parantTypeItem.typename
                timeSlot = btnDateSelect.text.toString()
                mAdapter?.selectList?.clear()
                mAdapter?.notifyDataSetChanged()
                btnAddMac.text =  "新增"
                mathineBean = null
                tvMacNo.text = "设备编码"
            }

        })
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)

        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }

}